var $customerTable = $('#customerTableList');//客户清单

//防止表头与表格不对齐
$(window).resize(function () {
    $customerTable.bootstrapTable('resetView');
});

$(function () {
    customerTableListInit();

    /* 高级筛选 */
    $('#filterContent').on('show.bs.collapse', function () {
        $('.btn-senior').html('<i class="mdi mdi-close"></i>关闭筛选');
    }).on('hide.bs.collapse', function () {
        $('.btn-senior').html('<i class="mdi mdi-sort-variant"></i>高级筛选');
    }).on('hidden.bs.collapse', function () {
        resetData('#filterContent');
    });
    $('.filter-content select').selectpicker({
        noneSelectedText: '请选择',
        sanitize: true,
        size: 8
    });
    $('.custom-group input[type="checkbox"]').click('click', function () {
        let customGroup = $(this).parents('.custom-group');
        if ($(this).prop('checked')) {
            // 自定义条件筛选
            customGroup.addClass('custom-active');
            customGroup.find('select').attr('disabled', 'disabled').find('option:first').prop('selected', 'selected');
            customGroup.find('select').selectpicker('refresh');
        } else {
            // 默认条件筛选
            customGroup.removeClass('custom-active');
            customGroup.find('select').removeAttr('disabled').selectpicker('refresh');
            $(this).parents('.custom-box').find('input[type="text"]').val('');
        }
    });
});

/**
 * 客户清单
 */
function customerTableListInit() {
    $customerTable.bootstrapTable('destroy');//先销毁表格
    $customerTable.bootstrapTable({
        classes: 'table table-hover table-bordered',
        url: '/customerController/customerList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: false,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'customerId',
        idField: 'customerId',
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'customerId', visible: false},
            /*{title: '全选', field: 'checked', align: 'center', checkbox: true, valign: 'middle', width: '6%'},*/
            {title: '序号', field: 'index', align: 'left', valign: 'middle', formatter: indexFormat,width: '60'},
            {title: '客户名称', field: 'customerName', align: 'left', valign: 'middle',width: 300},
            {title: '客户类型', field: 'customerType', align: 'left', valign: 'middle', width: '180', formatter: customerTypeFormat},
            {title: '所在地区', field: 'provinceName', align: 'left', valign: 'middle', width: '120', sortable: true,},
            // {title: '创建时间', field: 'createTm', align: 'left', valign: 'middle'},
            // {title: '客户级别', field: 'customerLevel', align: 'left', valign: 'middle'},
           /* {title: '联系人数量', field: 'contactPersonCount', align: 'right', valign: 'middle',width: 100,sortable: true,},
            {title: '跟进次数', field: 'followCount', align: 'right', valign: 'middle',width: 100, sortable: true,},*/
            // {title: '目前状态', field: 'currentStatus', align: 'left', valign: 'middle', formatter: currentStatusFormat},
            {title: '标签', field: 'tag', align: 'left', valign: 'middle',width:500,formatter: tagFormat},
            {title: '操作', field: 'operate', align: 'right', events: operateEvents, formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

function tagFormat(value){
    if(value != null && value != ''){
        var valueList =  value.split(',');
        if(valueList.length>5){
            valueList = valueList.slice(0,5)
        }
        let html = '';
        $.each(valueList,function(index,item){
            html +=  '<span class="tags">'+ item +'</span>';
        })

        return html;
    }else if(value == null || value  == ''){
        return '-'
    }


}
/**
 * 拼接客户表格查询条件参数
 * @param params
 * @returns {*}
 */
function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.userSystemIdent = 'user';//用户系统标识:用户系统客户清单只显示未领取客户

    //普通搜索条件
    params.customerPoolId = $('#customerPoolId').val();
    params.customerName = $.trim($('#customerName').val());
    return params;
}

/**
 * 搜索点击事件
 */
function searchCustomerTableList(type){
    if (type == 1) {//普通搜索点击事件
        $customerTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
        // 点击搜索重置表单 需传入高级搜索id #filterContent
        resetData('#filterContent');
        $('#filterContent').collapse('hide');
    } else {//高级搜索点击事件
        $customerTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: advancedQueryParams});
    }
}

/**
 * 高级搜索点击事件
 */
function advancedQueryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.userSystemIdent = 'user';//用户系统标识:用户系统客户清单只显示未领取客户

    //清空普通搜索条件
    $('#customerName').val('');

    var industry = $('#industrySelect option:selected').val();//行业
    var companyType = $('#companyTypeSelect option:selected').val();//企业类型

    var yearsEstablishmentSelect = $('#yearsEstablishmentSelect option:selected').val();//成立年限
    /**自定义成立年限**/
    var beginYearsEstablishmentCustom = $('#beginYearsEstablishment').val();
    var endYearsEstablishmentCustom = $('#endYearsEstablishment').val();
    var beginYearsEstablishment;
    var endYearsEstablishment;
    if(yearsEstablishmentSelect == 1){//1年内
        endYearsEstablishment = 0;
    }else if(yearsEstablishmentSelect == 2){//1-3年
        beginYearsEstablishment = 1;
        endYearsEstablishment = 3
    }else if(yearsEstablishmentSelect == 3){//3-5年
        beginYearsEstablishment = 3;
        endYearsEstablishment = 5;
    }else if(yearsEstablishmentSelect == 4){//5-10年
        beginYearsEstablishment = 5;
        endYearsEstablishment = 10;
    }else if(yearsEstablishmentSelect == 5){//10年以上
        beginYearsEstablishment = 11;
    }

    if(beginYearsEstablishmentCustom){
        beginYearsEstablishment = beginYearsEstablishmentCustom;
    }
    if(endYearsEstablishmentCustom){
        endYearsEstablishment = endYearsEstablishmentCustom;
    }

    var registeredCapitalSelect = $('#registeredCapitalSelect option:selected').val();//注册资本
    /**自定以注册资本**/
    var beginRegisteredCapitalCustom = $('#beginRegisteredCapital').val();
    var endRegisteredCapitalCustom = $('#endRegisteredCapital').val();
    var beginRegisteredCapital;
    var endRegisteredCapital;
    if(registeredCapitalSelect){
        if(registeredCapitalSelect == 1){//100万以内
            endRegisteredCapital = 99;
        }else if(registeredCapitalSelect == 2){//100万-500万
            beginRegisteredCapital = 100;
            endRegisteredCapital = 500;
        }else if(registeredCapitalSelect == 3){//500万-1000万
            beginRegisteredCapital = 500;
            endRegisteredCapital = 1000;
        }else if(registeredCapitalSelect == 4){//1000万-3000万
            beginRegisteredCapital = 1000;
            endRegisteredCapital = 3000;
        }else if(registeredCapitalSelect == 5){//3000万-5000万
            beginRegisteredCapital = 3000;
            endRegisteredCapital = 5000;
        }else if(registeredCapitalSelect == 6){//5000万以上
            beginRegisteredCapital = 5001;
        }
    }
    if(beginRegisteredCapitalCustom ){
        beginRegisteredCapital = beginRegisteredCapitalCustom;
    }
    if(endRegisteredCapitalCustom ){
        endRegisteredCapital = endRegisteredCapitalCustom;
    }

    var insuredNumbersSelect = $('#insuredNumbersSelect option:selected').val();//参保人数
    /**自定义参保人数**/
    var beginInsuredNumbersCustom = $('#beginInsuredNumbers').val();
    var endInsuredNumbersCustom = $('#endInsuredNumbers').val();
    var beginInsuredNumbers;
    var endInsuredNumbers;
    if(insuredNumbersSelect){
        if(insuredNumbersSelect == 1){//5人以下
            endInsuredNumbers = 4;
        }else if(insuredNumbersSelect == 2){//5-10人
            beginInsuredNumbers = 5;
            endInsuredNumbers = 10;
        }else if(insuredNumbersSelect == 3){//10-20人
            beginInsuredNumbers = 10;
            endInsuredNumbers = 20;
        }else if(insuredNumbersSelect == 4){//20-100人
            beginInsuredNumbers = 20;
            endInsuredNumbers = 100;
        }else if(insuredNumbersSelect == 5){//100-500人
            beginInsuredNumbers = 100;
            endInsuredNumbers = 500;
        }else if(insuredNumbersSelect == 6){//500-1000人
            beginInsuredNumbers = 500;
            endInsuredNumbers = 1000;
        }else if(insuredNumbersSelect == 7){//1000人以上
            beginInsuredNumbers = 1001;
        }
    }
    if(beginInsuredNumbersCustom ){
        beginInsuredNumbers = beginInsuredNumbersCustom;
    }
    if(endInsuredNumbersCustom ){
        endInsuredNumbers = endInsuredNumbersCustom;
    }

    var contactPersonPhone =  $('#isExistContactPersonPhone option:selected').val();//是否有联系电话
    var contactPerson =  $('#isExistContactPerson option:selected').val();//是否有联系人
    var email =  $('#isExistCompanyEmail option:selected').val();//是否有联系邮箱

    params.customerPoolId = $('#customerPoolId').val();
    params.industry = industry;
    params.companyType = companyType;
    params.beginYearsEstablishment = beginYearsEstablishment;
    params.endYearsEstablishment = endYearsEstablishment;
    params.beginRegisteredCapital = beginRegisteredCapital;
    params.endRegisteredCapital = endRegisteredCapital;
    params.beginInsuredNumbers = beginInsuredNumbers;
    params.endInsuredNumbers = endInsuredNumbers;
    params.contactPersonPhone = contactPersonPhone;
    params.contactPerson = contactPerson;
    params.email = email;
    params.tag = $.trim($('#tag').val());
    //params.currentStatus = $('#currentStatusSelect option:selected').val();//目前状态
    params.provinceName = $.trim($('#provinceName').val());
    params.cityName = $.trim($('#cityName').val());
    params.countyName = $.trim($('#countyName').val());
    return params;
}

/**
 * 目前状态
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function currentStatusFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (0 == value) {
        return "未领取";
    } else if (1 == value) {
        return "已领取";
    } else if (2 == value) {
        return "已分配";
    } else if (3 == value){
        return "自建客户";
    }
}

/**
 * 客户类型(0企业客户 1个人客户)
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function customerTypeFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (0 == value) {
        return "<span class='label label-success-light'>企业客户</span>";
    } else if (1 == value) {
        return "<span class='label label-info-light'>个人客户</span>";
    }
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    return '<button type="button" id="receive" class="btn btn-default"><i class="mdi mdi-stackoverflow"></i>领取</button>';
}

/**
 * 自定义操作列事件
 */
window.operateEvents = {
    //领取
    'click #receive': function (e, value, row, index) {
        var poolState = $("#poolState").val();
        var currentStatus = row.currentStatus;
        if (poolState == 2) {
            $.alert("客户池已停用不能领取！");
            return;
        }
        if (currentStatus == '1') {
            $.alert("客户已领取，不能领取！");
            return;
        } else if (currentStatus == '2') {
            $.alert("客户已分配，不能领取！");
            return;
        } else if (currentStatus == '3') {
            $.alert("自建客户，不能领取！");
            return;
        }
        if (currentStatus != '0') {
            $.alert('客户目前状态未处于”未领取“状态，不能领取！');
            return;
        }
        receiveCustomer(row.customerId);
    },
};

/**
 * 客户公海-客户清单-领取
 */
function receiveCustomer(customerId) {
    //客户池id
    var customerPoolId = $('#customerPoolId').val();
    var nature = $('#nature').val();//性质：1-全国公有池；2-分公司公有池；
    var affiliatedCompanyId = $('#affiliatedCompanyId').val();//全国公有池关联公司id
    $.alert({
        title: '提示',
        content: "确定要领取吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/customerController/receiveCustomer",
                        data: {
                            customerId: customerId,
                            customerPoolId: customerPoolId,
                            nature: nature,
                            affiliatedCompanyId: affiliatedCompanyId
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.data == 'C00001') {
                                $.alert('该客户不能领取!');
                            } else if (data.data == 'C00002') {
                                $.alert('您的客户容量已满,不能领取!');
                            } else if (data.data == 'C00003') {
                                $.alert('超过该客户池最大领取量,不能领取!');
                            } else if (data.data == 'C00004') {
                                $.alert('该客户暂不能领取!');
                            } else if (data.data == 'C00005') {
                                $.alert('客户领取过于频繁!');
                            } else if (data.data == 'C00007') {
                                $.alert('该客户暂不能领取!');
                            } else if (data.data == 'C00008') {
                                $.alert('客户已锁定!');
                            } else if (data.data == 'C00006') {
                                $.alert('领取成功!');
                                $customerTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                            } else {
                                $.alert('领取失败，请稍后再试!');
                            }
                        },
                        error: function () {
                            $.alert('领取异常，请稍后再试!');
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    })
}

//  重置
function resetData(_this) {
    let searchForm = '';
    if($(_this).parents('#filterContent').context == document) {
        searchForm = $(_this);
    }else{
        searchForm = $(_this).parents('#filterContent');
    }

    // 重置表单内容
    searchForm.find('input[type="text"]').val('');
    searchForm.find('select').find('option:first').prop('selected', 'selected');
    // 刷新下拉菜单selectpicker控件
    searchForm.find('select').selectpicker('refresh');
    // 重置自定义筛选条件
    searchForm.find('.custom-group').find('input[type="checkbox"]').prop('checked', false);
    searchForm.find('.custom-group').removeClass('custom-active').find('select').removeAttr('disabled').selectpicker('refresh');
    searchForm.find('.custom-group').find('input[type="text"]').val('');

    // 点击重置按钮时，刷线table内容
    if($(_this).parents('#filterContent').context !== document) {
        searchCustomerTableList();
    }
}


